package online.longzipeng.cinemasys.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import online.longzipeng.cinemasys.common.annotion.NeedPermissions;
import online.longzipeng.cinemasys.common.exception.AppException;
import online.longzipeng.cinemasys.common.result.ResponseEnum;
import online.longzipeng.cinemasys.common.result.Result;
import online.longzipeng.cinemasys.entity.Role;
import online.longzipeng.cinemasys.service.RoleService;
import online.longzipeng.cinemasys.vo.role.RoleSaveVO;
import online.longzipeng.cinemasys.vo.role.RoleUpdateVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lzp
 * @since 2021-04-08
 */
@RestController
@RequestMapping("/role")
@Api(value = "角色相关接口",description = "角色相关接口",tags = "角色相关接口")
public class RoleController {

    @Autowired
    RoleService roleService;

    @PostMapping("/save")
    @NeedPermissions("role:save")
    @ApiOperation("新增角色")
    public Result save(@Valid @RequestBody RoleSaveVO roleSaveVO){
        Role role = new Role();
        BeanUtils.copyProperties(roleSaveVO,role);
        roleService.add(role);
        return Result.success(null,"角色添加成功！！");
    }

    @GetMapping("/delete-one")
    @NeedPermissions("role:delete")
    @ApiOperation("删除角色")
    public Result deleteOne(@ApiParam(value = "角色id",required = true)Long id){
        try {
            roleService.removeById(id);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppException(ResponseEnum.FAILED);
        }
        return Result.success(null,"角色删除成功！！");
    }

    @GetMapping("/delete")
    @NeedPermissions("role:delete")
    @ApiOperation("删除多个角色")
    public Result deleteOne(@ApiParam(value = "角色id数组",required = true)Long[] ids){
        List<Long> idList = Arrays.stream(ids).collect(Collectors.toList());
        try {
            roleService.removeByIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppException(ResponseEnum.FAILED);
        }
        return Result.success(null,"角色删除成功！！");
    }

    @PostMapping("/update")
    @NeedPermissions("role:update")
    @ApiOperation("修改角色")
    public Result update(@Valid @RequestBody RoleUpdateVO roleUpdateVO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleUpdateVO,role);
        roleService.updateRole(role);
        return Result.success(null,"角色修改成功！！");
    }

}
